﻿using System;
using System.IO.Ports;
using System.Net.NetworkInformation;
using System.Windows.Forms;

namespace SerialServerManager
{
    public partial class FrmAddServer : Form
    {
        // 替换原有独立属性为配置对象
        public SerialConfig Config { get; private set; } = new SerialConfig();

        public FrmAddServer()
        {
            InitializeComponent();
            LoadLocalIpAddresses(); // 窗体加载时自动获取IP
            InitializeSerialParams();
            InitializeReconnectSettings(); // 初始化重连设置
        }

        // 加载本地IP地址（窗体创建时自动执行）
        private void LoadLocalIpAddresses()
        {
            cmbIp.Items.Clear();
            cmbIp.Items.Add("0.0.0.0"); // 监听所有网卡
            cmbIp.Items.Add("127.0.0.1");

            try
            {
                foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
                {
                    // 筛选活动的以太网和无线网卡
                    if (nic.OperationalStatus == OperationalStatus.Up &&
                        (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet ||
                         nic.NetworkInterfaceType == NetworkInterfaceType.Wireless80211))
                    {
                        // 获取IPv4地址
                        foreach (var addr in nic.GetIPProperties().UnicastAddresses)
                        {
                            if (addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                            {
                                string ip = addr.Address.ToString();
                                if (!cmbIp.Items.Contains(ip))
                                    cmbIp.Items.Add(ip);
                            }
                        }
                    }
                }

                // 默认选择第一个有效IP
                cmbIp.SelectedIndex = cmbIp.Items.Count > 2 ? 2 : 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取IP失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 初始化串口参数
        private void InitializeSerialParams()
        {
            // 加载可用串口
            cmbCom.Items.AddRange(SerialPort.GetPortNames());
            if (cmbCom.Items.Count > 0)
                cmbCom.SelectedIndex = 0;

            // 波特率
            cmbBaudRate.Items.AddRange(new object[] { 9600, 19200, 38400, 57600, 115200 });
            cmbBaudRate.SelectedItem = 9600;

            // 校验位
            cmbParity.Items.AddRange(Enum.GetNames(typeof(Parity)));
            cmbParity.SelectedItem = Parity.None.ToString();

            // 数据位
            cmbDataBits.Items.AddRange(new object[] { 7, 8 });
            cmbDataBits.SelectedItem = 8;

            // 停止位
            cmbStopBits.Items.AddRange(Enum.GetNames(typeof(StopBits)));
            cmbStopBits.SelectedItem = StopBits.One.ToString();

            // 端口默认值
            txtPort.Text = "8082";
        }

        // 复选框状态变化事件
        private void chkAutoReconnect_CheckedChanged(object sender, EventArgs e)
        {
            // 根据复选框状态启用/禁用输入框
            bool isEnabled = chkAutoReconnect.Checked;
            txtReconnectInterval.Enabled = isEnabled;
            txtMaxReconnect.Enabled = isEnabled;
        }
        // 初始化重连设置
        private void InitializeReconnectSettings()
        {
            chkAutoReconnect.Checked = true; // 默认启用
            txtReconnectInterval.Text = "3000"; // 默认3秒
            txtMaxReconnect.Text = "0"; // 默认无限重试
        }

        // 确认按钮
        private void btnOK_Click(object sender, EventArgs e)
        {
            // 验证COM口
            if (string.IsNullOrEmpty(cmbCom.Text))
            {
                MessageBox.Show("请选择COM口", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cmbCom.Focus();
                return;
            }

            // 验证IP地址
            if (cmbIp.SelectedItem == null)
            {
                MessageBox.Show("请选择IP地址", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cmbIp.Focus();
                return;
            }

            // 验证端口
            if (!int.TryParse(txtPort.Text, out int port) || port < 1 || port > 65535)
            {
                MessageBox.Show("请输入有效的端口号（1-65535）", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtPort.Focus();
                return;
            }

            // 验证重连间隔
            if (!int.TryParse(txtReconnectInterval.Text, out int interval) || interval < 1000)
            {
                MessageBox.Show("请输入有效的重连间隔（至少1000ms）", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtReconnectInterval.Focus();
                return;
            }

            // 验证最大重连次数
            if (!int.TryParse(txtMaxReconnect.Text, out int maxTimes) || maxTimes < 0)
            {
                MessageBox.Show("请输入有效的最大重连次数（0-999）", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtMaxReconnect.Focus();
                return;
            }

            // 保存配置到Config对象
            Config.ComPort = cmbCom.Text;
            Config.IpAddress = cmbIp.SelectedItem.ToString();
            Config.Port = port;
            Config.BaudRate = (int)cmbBaudRate.SelectedItem;
            Config.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.SelectedItem.ToString());
            Config.DataBits = (int)cmbDataBits.SelectedItem;
            Config.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.SelectedItem.ToString());

            // 保存重连配置
            Config.AutoReconnect = chkAutoReconnect.Checked;
            Config.ReconnectInterval = interval;
            Config.MaxReconnectTimes = maxTimes;

            DialogResult = DialogResult.OK;
            Close();
        }

        // 取消按钮
        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }
    }
}